package utility;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.oreilly.servlet.MultipartRequest;

public class Uploader {
	private MultipartRequest multi;
	private String extension;
	private String savePath;
	private String preFix;
	

	public String getPreFix() {
		return preFix;
	}
	public void setPreFix(String preFix) {
		this.preFix = preFix;
	}
	
	public MultipartRequest getMutilPathRequest() {
		return multi;
	}

	public String getExtension() {
		return extension;
	}

	public Uploader(HttpServletRequest request, String pathFile)
			throws IOException {
		this.setPreFix("fbm");
		savePath = request.getSession().getServletContext()
				.getRealPath(pathFile);
		File path = new File(savePath);
		if (!path.exists()) {
			path.mkdir();
		}
		multi = new MultipartRequest(request, savePath, 5 * 1024 * 1024); // Max = 5 MB in Three Files
	}

	public boolean upload(String fileName) throws IOException {

		Enumeration filenames = multi.getFileNames();

		if (filenames.hasMoreElements()) {
			File file = multi.getFile((String) filenames.nextElement());
			if (file == null)
				return false;
			extension = file.getName().substring(
					file.getName().lastIndexOf(".") + 1);
			String x=savePath + "/"+preFix + fileName + "." + extension;
			File newName = new File(x);
			
			if(newName.exists()){
				newName.delete();
			}
			if (file.renameTo(new File(x))) {
				System.out.println("Has been rename successfully.");
				System.out.println(newName.getName());
				System.out.println(file.getAbsolutePath());
			} else {
				System.out.println("Can not rename!!!");
			}

		} else {
			System.out.println(" No file");
		}
		return true;
	}

	}
